<template>
	<view class="page">

		<view class="wrapper font15">
			<!-- 基本信息 -->
			<view class="info-box">
				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>公司名称:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.comname" type="text" placeholder="请输入公司名称" maxlength="100" />
					</view>
				</view>

				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>公司法人姓名:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.peoname" type="text" placeholder="请输入法人姓名" maxlength="20" />
					</view>
				</view>

				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write" v-show="showIdCard">*</text>
						<text>法人身份证号:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.bankNumber" type="text" placeholder="请输入法人身份证号" />
					</view>
				</view>
			</view>

			<!-- 身份证照片 -->
			<view class="id-card">
				<view >
					<text>法人身份证照片:</text>
				</view>
				<view class="photo-container">
					<view class="photo-box" @click="chooseIdImage">
						<image :src="formData.idFront || serverAddress+'/img/icon-sfz(zheng)@2x.png'" class="id-front" />
					</view>
				</view>
			</view>

			<!-- 地址信息 -->
			<view class="info-box">
				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>公司所在地区:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.trigger4" readonly type="text" placeholder="请选择"
							@click="showRegionPicker" />
					</view>
				</view>

				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>公司详细地址:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.shopDetailAddr" type="text" placeholder="请输入公司详细地址" maxlength="40" />
					</view>
				</view>
			</view>

			<!-- 营业执照 -->
			<view class="id-card">
				<view>
					<text class="must-write">*</text>
					<text>营业执照</text>
				</view>
				<view class="photo-container">
					<view class="photo-box" @click="chooseLicenseImage">
						<image :src="formData.permission || serverAddress+'/img/permission1.png'" class="permission" />
					</view>
				</view>
			</view>

			<!-- 公司LOGO -->
			<view class="id-card">
				<view class="label-box">
					<text>公司LOGO</text>
				</view>
				<view class="photo-container">
					<view class="photo-box" @click="chooseLogoImage">
						<image :src="formData.logo || serverAddress+'/img/icon-photo1（tianxieshangjia）@2x.png'" class="logo-img" />
					</view>
				</view>
			</view>

			<!-- 银行信息 -->
			<view class="info-box">
				<view class="layouts display-flex">
					<view class="label-box card-type-label">
						<text class="must-write">*</text>
						<text>卡类型:</text>
					</view>
					<view class="card-type-box">
						<view class="card-type">
							<view v-for="(item, index) in cardTypes" :key="index" class="card-type-item"
								@click="selectCardType(item.value)">
								<image
									:src="formData.cardType === item.value ? serverAddress+'/img/radio-checked.png' : serverAddress+'/img/radio.png'"
									class="radio-icon" />
								<text>{{ item.label }}</text>
							</view>
						</view>
					</view>
				</view>

				<view class="layouts display-flex" v-show="showBankName">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>银行户名:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.bankname" type="text" placeholder="请输入银行户名" maxlength="40" />
					</view>
				</view>

				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>银行卡号:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.banknum" type="text" placeholder="请输入银行卡号" />
					</view>
				</view>

				<view class="layouts display-flex" v-show="showBank">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>开户行:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.bank" type="text" placeholder="开户行" maxlength="40" />
					</view>
				</view>

				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>联系人姓名:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.bankcardname" type="text" placeholder="请输入联系人姓名" maxlength="20" />
					</view>
				</view>

				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>联系人电话:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.banktell" type="text" placeholder="请输入联系人电话" />
					</view>
				</view>

				<view class="layouts display-flex">
					<view class="label-box">
						<text class="must-write">*</text>
						<text>联系人邮箱:</text>
					</view>
					<view class="input-box">
						<input v-model="formData.bankemile" type="text" placeholder="请输入联系人邮箱" />
					</view>
				</view>
			</view>

			<!-- 下一步按钮 -->
			<view class="next-step" @click="nextStep">
				<text>下一步</text>
			</view>
		</view>

		<!-- 地区选择器 -->
		<picker-view v-if="showPicker" class="region-picker" @change="onRegionChange">
			<picker-view-column>
				<view v-for="(province, index) in regionData" :key="index" class="picker-item">
					{{ province.value }}
				</view>
			</picker-view-column>
			<picker-view-column>
				<view v-for="(city, index) in cityData" :key="index" class="picker-item">
					{{ city.value }}
				</view>
			</picker-view-column>
			<picker-view-column>
				<view v-for="(district, index) in districtData" :key="index" class="picker-item">
					{{ district.value }}
				</view>
			</picker-view-column>
		</picker-view>
	</view>
</template>

<script>
	import {
		merchantApi,
		commonApi
	} from '@/api/index.js'
	import request from '@/api/request.js'
import {
		inject
	} from 'vue'
	export default {
		data() {
			return {
				serverAddress: inject('$serverAddress', ''),
				formData: {
					comname: '',
					peoname: '',
					bankNumber: '',
					trigger4: '',
					shopDetailAddr: '',
					bankname: '',
					banknum: '',
					bank: '',
					bankcardname: '',
					banktell: '',
					bankemile: '',
					cardType: '3', // 默认对公账号
					idFront: '',
					permission: '',
					logo: ''
				},
				cardTypes: [{
						label: '对公账号',
						value: '3'
					},
					{
						label: '对私非法人',
						value: '2'
					},
					{
						label: '对私法人',
						value: '1'
					}
				],
				regionData: [],
				cityData: [],
				districtData: [],
				selectedRegion: [],
				showPicker: false,
				addrIdarr: null
			}
		},
		computed: {
			showIdCard() {
				return this.formData.cardType === '1'
			},
			showBankName() {
				return this.formData.cardType !== '1'
			},
			showBank() {
				return this.formData.cardType === '3'
			}
		},
		onLoad() {
			this.loadRegionData()
			this.loadStoredData()
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 加载地区数据
			async loadRegionData() {
				try {
					const res = await commonApi.getAllRegion()
					if (res.r === 0) {
						this.regionData = res.data.gr.map(item => ({
							...item,
							value: item.region_name,
							childs: item.child.map(city => ({
								...city,
								value: city.region_name,
								childs: city.child.map(district => ({
									...district,
									value: district.region_name
								}))
							}))
						}))
						this.cityData = this.regionData[0]?.childs || []
						this.districtData = this.cityData[0]?.childs || []
					}
				} catch (error) {
					console.error('加载地区数据失败:', error)
				}
			},

			// 加载本地存储数据
			loadStoredData() {
				const storedData = uni.getStorageSync('changjiaobj')
				if (storedData) {
					this.formData = {
						...this.formData,
						...storedData
					}
					this.addrIdarr = storedData.addrIdarr
				}
			},

			// 显示地区选择器
			showRegionPicker() {
				this.showPicker = true
			},

			// 地区选择变化
			onRegionChange(e) {
				const [provinceIndex, cityIndex, districtIndex] = e.detail.value
				const province = this.regionData[provinceIndex]
				const city = province.childs[cityIndex]
				const district = city.childs[districtIndex]

				this.addrIdarr = [province, city, district]
				this.formData.trigger4 = `${province.value}-${city.value}-${district.value}`
				this.showPicker = false
			},

			// 选择卡类型
			selectCardType(type) {
				this.formData.cardType = type
				if (type === '1') {
					// 对私法人，银行户名自动填入法人姓名
					this.formData.bankname = this.formData.peoname
				} else {
					this.formData.bankname = ''
				}
			},

			// 选择身份证照片
			chooseIdImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadImage(res.tempFilePaths[0], 'idFront')
					}
				})
			},

			// 选择营业执照
			chooseLicenseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadImage(res.tempFilePaths[0], 'permission')
					}
				})
			},

			// 选择公司LOGO
			chooseLogoImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadImage(res.tempFilePaths[0], 'logo')
					}
				})
			},

			// 上传图片
			async uploadImage(filePath, type) {
				uni.showLoading({
					title: '上传中...'
				})
				try {
					// 使用request.js中的uploadImage方法
					const imagePath = await request.uploadImage({
						filePath,
						name: 'file'
					})
					this.formData[type] = imagePath
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('上传失败:', error)
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 表单验证
			validateForm() {
				const {
					comname,
					peoname,
					trigger4,
					shopDetailAddr,
					bankname,
					banknum,
					bankcardname,
					banktell,
					bankemile,
					cardType,
					bankNumber,
					bank
				} = this.formData

				if (!comname.trim()) {
					uni.showToast({
						title: '公司名不能为空！',
						icon: 'none'
					})
					return false
				}

				if (!peoname.trim()) {
					uni.showToast({
						title: '法人姓名不能为空!',
						icon: 'none'
					})
					return false
				}

				if (!trigger4.trim()) {
					uni.showToast({
						title: '请选择公司地址！',
						icon: 'none'
					})
					return false
				}

				if (!shopDetailAddr.trim()) {
					uni.showToast({
						title: '请输入详细地址！',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.permission) {
					uni.showToast({
						title: '请上传营业执照！',
						icon: 'none'
					})
					return false
				}

				if (!bankname.trim()) {
					uni.showToast({
						title: '请输入银行户名！',
						icon: 'none'
					})
					return false
				}

				const cleanBankNum = banknum.replace(/\s+/g, "")
				if (cleanBankNum.length < 14 || cleanBankNum.length > 19) {
					uni.showToast({
						title: '请输入正确的公司银行卡号！',
						icon: 'none'
					})
					return false
				}

				if (cardType === '3' && !bank.trim()) {
					uni.showToast({
						title: '请输入开户银行！',
						icon: 'none'
					})
					return false
				}

				if (!bankcardname.trim()) {
					uni.showToast({
						title: '请输入联系人姓名！',
						icon: 'none'
					})
					return false
				}

				const phoneReg = /^1[3-9]\d{9}$/
				if (!phoneReg.test(banktell.trim())) {
					uni.showToast({
						title: '请输入正确的联系人电话!',
						icon: 'none'
					})
					return false
				}

				const emailReg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
				if (!emailReg.test(bankemile.trim())) {
					uni.showToast({
						title: '请输入联系人邮箱!',
						icon: 'none'
					})
					return false
				}

				if (cardType === '1') {
					if (!bankNumber.trim()) {
						uni.showToast({
							title: '请输入法人身份证号！',
							icon: 'none'
						})
						return false
					}
					const idReg =
						/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
					if (!idReg.test(bankNumber)) {
						uni.showToast({
							title: '请输入正确的身份证号！',
							icon: 'none'
						})
						return false
					}
				}

				return true
			},

			// 下一步
			nextStep() {
				if (!this.validateForm()) {
					return
				}

				// 保存数据到本地存储
				const saveData = {
					...this.formData,
					addrIdarr: this.addrIdarr
				}
				uni.setStorageSync('changjiaobj', saveData)

				// 跳转到下一页
				uni.navigateTo({
					url: '/pages/identity/changjia-b'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background: #eeeeee;
		min-height: 100vh;
	}

	.header-bag {
		display: flex;
		align-items: center;
		height: 88rpx;
		background: #fff;
		position: relative;

		.back {
			width: 40rpx;
			height: 40rpx;
			margin-left: 30rpx;
		}

		.header-center {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);

			text {
				font-size: 36rpx;
				color: #333;
			}
		}
	}

	.wrapper {
		padding-bottom: 40rpx;
	}

	.font15 {
		font-size: 30rpx;
	}

	.info-box {
		background: #ffffff;
		margin-top: 20rpx;
		padding: 0 30rpx;
		border-bottom: 1px solid #e8e8e8;
	}

	.layouts {
		height: 90rpx;
		line-height: 90rpx;
		border-bottom: 1px solid #e8e8e8;

		&:last-child {
			border-bottom: none;
		}
	}

	.display-flex {
		display: flex;
		align-items: center;
	}

	.must-write {
		color: red;
		
	}

	.label-box {
		width: 30%;
		position: relative;
		margin-left: 30rpx;

		.must-write {
			color: red;
			position: absolute;
			left: -20rpx;
			top: 5rpx;
		}
	}

	.card-type-label {
		width: 30%;
	}

	.input-box {
		width: 70%;

		input {
			height: 50rpx;
			line-height: 50rpx;
			width: 100%;
			color: #4b4b4b;
			font-size: 26rpx;
		}
	}

	.card-type-box {
		width: 70%;
	}

	.card-type {
		display: flex;
		position: relative;
		left: -80rpx;
	}

	.card-type-item {
		float: left;
		// padding-left: 50rpx;
		font-size: 24rpx;
		// background: url('/static/radio.png') no-repeat 20rpx 35rpx;
		background-size: 22rpx 22rpx;
		margin-right: 20rpx;

		&.active {
			// background: url('/static/radio-checked.png') no-repeat 20rpx 35rpx;
			background-size: 22rpx 22rpx;
		}

		.radio-icon {
			width: 22rpx;
			height: 22rpx;
			margin-right: 8rpx;
		}
	}

	.id-card {
		font-size: 30rpx;
		background: #ffffff;
		margin-top: 20rpx;
		padding: 30rpx;

		.label-box {
			margin-left: 30rpx;
			margin-bottom: 30rpx;

			.must-write {
				position: absolute;
				left: -20rpx;
				top: 5rpx;
			}
		}
	}

	.photo-container {
		margin-left: 20rpx;
	}

	.photo-box {
		position: relative;
		width: 305rpx;
		height: 220rpx;
		// float: left;
		margin-right: 40rpx;
	}

	.id-front,
	.permission {
		width: 305rpx;
		height: 193rpx;
		margin-top: 30rpx;
	}

	.logo-img {
		width: 218rpx;
		height: 192rpx;
	}

	.next-step {
		width: 690rpx;
		line-height: 90rpx;
		height: 90rpx;
		color: white;
		background: #ff2e00;
		border-radius: 10rpx;
		text-align: center;
		margin: 0 auto;
		margin-top: 20rpx;
	}

	.region-picker {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 500rpx;
		background: #fff;
		z-index: 999;
	}

	.picker-item {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		font-size: 30rpx;
	}
</style>